<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="二级集团：">
                        <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="企业名称：" prop="companyId">
                        <company-select v-model="dataToQuery.companyName" style="width:100%" />
                        <!-- <div>
                            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgname='setQueryOrgName' :orgTree="true"
                                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                        </div> -->
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label='绩效管理考核单元编号：'>
                        <Input class='query-form-el' type='text' v-model='dataToQuery.unitNo'></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">

                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <download-button :api="exportUrl" :queryForm="dataToQuery" />
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
               :loading='pageStatus.loading' @on-expand="onExpand"
               border :columns="columns1" :data="dataTable">
        </Table>
        <!--分页-->
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
                <!-- <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange1" @on-page-size-change="pageSizeChange1" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator /> -->
            </Col>
        </Row>
        <!--新增、修改、详情-->
        <Modal :title="mode == 'view' ?'高层建筑登记表详情':'高层建筑登记表'" :transfer=false :mask-closable="false"
               v-model="dialogShow" v-if="dataToView && dialogShow" :width=850 class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'"
                          :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                          :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?140:null">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='企业名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                                    <cascader-dom v-else ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true" :currentOrgId="dataToView.companyId"
                                                  :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='绩效管理考核单元编号：' prop='unitNo'>
                                    <div v-if="mode === 'view'">{{ dataToView.unitNo }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写绩效管理考核单元编号" type='text' v-model='dataToView.unitNo'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='分公司/项目名称：' prop='entryName'>
                                    <div v-if="mode === 'view'">{{ dataToView.entryName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写分公司/项目名称" type='text' v-model='dataToView.entryName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='所在位置：' prop='location'>
                                    <div v-if="mode === 'view'">{{ dataToView.location }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写所在位置" type='text' v-model='dataToView.location'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='管理总面积（m²）：' prop='areas'>
                                    <div v-if="mode === 'view'">{{ dataToView.areas }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写管理总面积（m²）" :min="0" v-model='dataToView.areas'></InputNumber>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>

                        <Row>
                            <Col span="23" class="query-form" style="margin-left: 15px">
                                <Button v-if="mode !== 'view'" class="ivu-btn-add" icon="md-add"
                                        @click="itemModel=true,itemAdd=true;detailItem={buildingHeight:0, upLayers:0,lowLayers:0,buildingArea:0,buildingNumber:0}">新增建筑详情</Button>
                                <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350" :columns="itemColumn"
                                       :data="dataToView.items">
                                </Table>
                            </Col>


                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                                           v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                                                v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :mask-closable="false" :transfer=false v-model="itemModel" :width=600 title="建筑详情"
               @on-cancel="itemModel=false,detailItem={}">
            <Row>
                <Col span="24">
                    <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="detailItem"
                          :rules="itemRuleCustom" label-position="top" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='建筑类别：' prop='category'>
                                    <div v-if="mode === 'view'">{{ detailItem.categoryName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写建筑类别" type='text' v-model='detailItem.category'></Input>-->
                                    <Select v-else class='' placeholder="请选择建筑类别" v-model='detailItem.category' label-in-value
                                            @on-change='(value)=>{detailItem.categoryName=value.label,detailItem.category=value.value}'>
                                        <Option v-for="item in dictMap.categoryList" :value="item.codingCodeId" :label="item.codingName" :key="item.codingCodeId">
                                            <span>{{ item.codingName }}</span>
                                            <!--<span style="float:right;color:#ccc">{{ item.note }}</span>-->
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='高层楼宇高度（m）：' prop='buildingHeight'>
                                    <div v-if="mode === 'view'">{{ detailItem.buildingHeight }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写高层楼宇高度（m）" :min="0" type='text' v-model='detailItem.buildingHeight'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='建筑物耐火等级：' prop='fireRating'>
                                    <div v-if="mode === 'view'">{{ detailItem.fireRating }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写建筑物耐火等级" type='text' v-model='detailItem.fireRating'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='地上层数（层）：' prop='upLayers'>
                                    <div v-if="mode === 'view'">{{ detailItem.upLayers }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写地上层数（层）" :min="0" type='text' v-model='detailItem.upLayers'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='地下层数（层）：' prop='lowLayers'>
                                    <div v-if="mode === 'view'">{{ detailItem.lowLayers }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写地下层数（层）" :min="0" type='text' v-model='detailItem.lowLayers'></InputNumber>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='面积（m²）：' prop='buildingArea'>
                                    <div v-if="mode === 'view'">{{ detailItem.buildingArea }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写面积（m²）" :min="0" type='text' v-model='detailItem.buildingArea'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='楼宇数量（栋）：' prop='buildingNumber'>
                                    <div v-if="mode === 'view'">{{ detailItem.buildingNumber }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写楼宇数量（栋）" :min="0" type='text' v-model='detailItem.buildingNumber'></InputNumber>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='消防设施年度检测情况：' prop='detection'>
                                    <div v-if="mode === 'view'">{{ detailItem.detection }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写建筑物耐火等级" type='text' v-model='detailItem.detection'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' @click="itemSubmit('itemForm')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false,detailItem={}">取消</Button>
                <!--<Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>-->
            </div>
        </Modal>


    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'

    export default {
        components: {cascaderDom},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                    {type:'expand', width:30,
                        fixed: 'left',
                        _disableExpand:true,
                        render:(h,params)=>{
                            return h('Table',{
                                props: {
                                    columns: [
                                        { key:'categoryName',title: '建筑类别',  align: 'center', minWidth: 120,  },
                                        { key:'buildingHeight',title: '高层楼宇高度（m）',  align: 'center', minWidth: 120,  },
                                        { key:'fireRating',title: '建筑物耐火等级',  align: 'center', minWidth: 120,  },
                                        { key:'upLayers',title: '地上层数（层）',  align: 'center', minWidth: 120,  },
                                        { key:'lowLayers',title: '地下层数（层）',  align: 'center', minWidth: 120,  },
                                        { key:'buildingArea',title: '面积（m²）',  align: 'center', minWidth: 120,  },
                                        { key:'buildingNumber',title: '楼宇数量（栋）',  align: 'center', minWidth: 120,  },
                                        { key:'detection',title: '防设施年度检测情况',  align: 'center', minWidth: 120,  },
                                    ],//表头
                                    data: params.row.items,//内部表格展示的数据
                                },
                            })//我这里使用的是表格，大家也可以根据自己的实际情况更换别的组件
                        }
                    },
                    {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'companyName',title: '单位名称',  align: 'center', minWidth: 120,  },
                    { key:'unitNo',title: '绩效管理考核单元编号',  align: 'center', minWidth: 120,  },
                    { key:'entryName',title: '分公司/项目名称',  align: 'center', minWidth: 120,  },
                    { key:'location',title: '所在位置',  align: 'center', minWidth: 120,  },
                    { key:'areas',title: '管理总面积（m²）',  align: 'center', minWidth: 120,  },

                    this.getActionColumns()
                ],
                ruleCustom: {
                    companyId: [ { required: true, message: '请填写单位名称', trigger: 'change',}],
                    unitNo: [ { required: true, message: '请填写绩效管理考核单元编号', trigger: 'change',}],
                    entryName: [ { required: true, message: '请填写分公司/项目名称', trigger: 'change',}],
                    location: [ { required: true, message: '请填写所在位置', trigger: 'change',}],
                    areas: [ { required: true, message: '请填写管理总面积（m²）', trigger: 'change',type:'number'}],
                },
                tableHeight: 10,
                dictMap:{},
                detailItem:{},
                itemModel:false,
                itemAdd:false,
                columns2: [
                    {title: '序号', width: 70, align: 'center', render: this.indexColumnsRender},
                    { key:'categoryName',title: '建筑类别',  align: 'center', minWidth: 120,  },
                    { key:'buildingHeight',title: '高层楼宇高度（m）',  align: 'center', minWidth: 120,  },
                    { key:'fireRating',title: '建筑物耐火等级',  align: 'center', minWidth: 120,  },
                    { key:'upLayers',title: '地上层数（层）',  align: 'center', minWidth: 120,  },
                    { key:'lowLayers',title: '地下层数（层）',  align: 'center', minWidth: 120,  },
                    { key:'buildingArea',title: '面积（m²）',  align: 'center', minWidth: 120,  },
                    { key:'buildingNumber',title: '楼宇数量（栋）',  align: 'center', minWidth: 120,  },
                    { key:'detection',title: '防设施年度检测情况',  align: 'center', minWidth: 120,  },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 110,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '13px',},
                                    on: {
                                        click: () => {
                                            this.detailItem = {...params.row}
                                            this.itemModel = true
                                            this.itemAdd = false
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '13px',color: 'red'},
                                    on: {
                                        click: () => {
                                            this.dataToView.items.splice(params.index,1)
                                        }
                                    }
                                }, '删除'),
                            ])
                        }
                    }
                ],
                itemRuleCustom: {
                    category: [ { required: true, message: '请填写建筑类别', trigger: 'change',}],
                    buildingHeight: [ { required: true, message: '请填写高层楼宇高度（m）', trigger: 'change',type:'number'}],
                    fireRating: [ { required: true, message: '请填写建筑物耐火等级', trigger: 'change',}],
                    upLayers: [ { required: true, message: '请填写地上层数（层）', trigger: 'change',type:'number'}],
                    lowLayers: [ { required: true, message: '请填写地下层数（层）', trigger: 'change',type:'number'}],
                    buildingArea: [ { required: true, message: '请填写面积（m²）', trigger: 'change',type:'number'}],
                    buildingNumber: [ { required: true, message: '请填写楼宇数量（栋）', trigger: 'change',type:'number'}],
                    detection: [ { required: true, message: '请填写消防设施年度检测情况', trigger: 'change'}],
                },
                // api
                exportUrl: Api.exportHighBuildingRegistration,
                queryUrl: Api.queryHighBuildingRegistration,
                deleteUrl: Api.deleteHighBuildingRegistration,
                updateUrl: Api.updateHighBuildingRegistration,
                saveUrl: Api.saveHighBuildingRegistration,
                buttonLoading: false,

            }
        },
        computed: {
            itemColumn() {
                const columns = [...this.columns2];
                const columns1 = []
                columns.forEach(item => {
                    if (this.mode !== 'view') {
                        columns1.push(item)
                    } else {
                        if (item.key !== 'action') {
                            columns1.push(item)
                        }
                    }
                })
                return columns1
            },
        },
        async mounted() {
            this.setTableHeight();
            await this.$http.get(Api.queryDictBycode+"env-00018",{}).then((res)=>{
                this.dictMap = {
                    'categoryList': res.data.data['env-00018'],
                }
            }).catch(e => {
                this.$Message.error("数据字典获取失败")
            });
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            itemSubmit(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                            title: '提示',
                            content: '<p>是否要提交？</p>',
                            onOk: () => {
                                let _this = this
                                _this.dataToView.items.splice()
                                if (_this.itemAdd) {
                                    _this.dataToView.items.push(_this.detailItem)
                                } else {
                                    _this.dataToView.items[_this.detailItem._index]= _this.detailItem
                                }
                                _this.itemModel = false
                            },
                            onCancel: () => {}
                        })
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },

            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {

                this.queryAjax();
            },
            submit(name) {
                // if (this.dataToView.staffNumber == '') this.dataToView.staffNumber = 0;
                if (this.dataToView.items.length < 1) {
                    this.$Message.warning('建筑详情至少填报一条');
                } else {
                    this.submitAjax(name);
                }
            },
            async beforeEditDialogOpen(data) {
                // data.row.hazardousWorkItemArr = data.row.hazardousWorkItems?data.row.hazardousWorkItems.split(','):[]
            },
            async beforeViewDialogOpen(data) {
                // data.row.hazardousWorkItemArr = data.row.hazardousWorkItems?data.row.hazardousWorkItems.split(','):[]
            },
            createEmptyDataToAdd() {
                return {
                    areas: 0,
                    id: this.get_uuid(),
                    idFiles: [],
                    items: [],
                }
            },
            async afterDataToViewInit() {
                // await this.getFiles1('id', 'examSelect');
            },

        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
